<?php
namespace app\index\controller;

use app\index\model\certifyNeed as CertifyNeedModel;
use app\index\model\certifyNeedEnum as CertifyNeedEnumModel;
use app\index\model\appKind as AppKindModel;

use think\Request;
use think\Db;

class CertifyNeed
{
    public function getBorderId($dataNum, $page, $kindName)
    {
        //根据页码和数据数目获取应查询数据的第一个 id     
        $boderId = 0;
        if ($page == 1) {
            $boderId = 0;
        }
        else {

            $allNotDataId = CertifyNeedModel::all(function ($query) use ($page, $dataNum, $kindName) {
                $query->where('kindName', $kindName)->limit($dataNum * ($page - 1))->order('id', 'asc');
            });
            $boderId = $allNotDataId[count($allNotDataId) - 1]['id'];
            
        }
        return $boderId;
    }

    public function getEnumValue($allNote)
    {
        //获取枚举值
        foreach ($allNote as $key => $value) {
            if ($value['infoType'] == 'enum') {
                $temp = CertifyNeedEnumModel::all(function ($query) use ($value) {
                    $query->where('kindName', $value['kindName'])->where('infoName', $value['infoName']);
                });
                $allValue = [];
                foreach ($temp as $k => $v) {
                    $allValue[] = $v['oneValue'];
                }
                $allNote[$key]['chooseValue'] = $allValue;
            }
            else {

            }
        }
        return $allNote;
    }
    public function getBasicNeed(Request $request)
    {
        //获取请求参数
        $dataNum = $request->param('dataNum');
        $page = $request->param('page');
        $keyName = $request->param('keyName');
        $keyWord = $request->param('keyWord');

        $boderId = $this->getBorderId($dataNum, $page, 'all');
        
        //初始化消息
        $message = '';
        $status = 0;

        //获取数据总条数
        $allNote = CertifyNeedModel::all(["belong" => "basic"]);
        $allNoteNum = count($allNote);
        
        $query = $keyName != '' ? 
        function ($query) use ($boderId, $dataNum, $keyName, $keyWord) {
            $query->where('belong', 'basic')->where('id', '>', $boderId)->where($keyName, $keyWord)->order('id', 'asc')->limit($dataNum);
        } :
        function ($query) use ($boderId, $dataNum) {
            $query->where('belong', 'basic')->where('id', '>', $boderId)->order('id', 'asc')->limit($dataNum);
        };
        //查询数据
        $allNote = CertifyNeedModel::all($query);
        $allNote = $this->getEnumValue($allNote);

        //认证分类的 chooseValue 加上所有的分类
        $allKind = AppKindModel::all();
        $chooseKind = [];
        foreach ($allKind as $key => $value) {
            $chooseKind[] = $value['kindName'];
        }
        foreach ($allNote as $key => $value) {
            if ($value['infoName'] == '认证分类') {
                $allNote[$key]['chooseValue'] = $chooseKind;
            }
            else {

            }
        }

        $message = 'get basic need success.';
        //返回消息
        $JsonData = controller("index/JsonData");
        $data = [
            'dataTotal' => $allNoteNum,
            'allCertifyNeed' => $allNote
        ];
        $json = $JsonData->getJsonData($status, $message, $data);
        return $json;
    }
    
    public function getExpertNeed(Request $request)
    {
        //获取请求参数
        $kindName = $request->param('kindName');
        $page = $request->param('page');
        $dataNum = $request->param('dataNum');
        $keyName = $request->param('keyName');
        $keyWord = $request->param('keyWord');

        $boderId = $this->getBorderId($dataNum, $page, $kindName);
        //初始化消息
        $message = '';
        $status = 0;

        //获取数据总条数
        $allNote = CertifyNeedModel::all(["kindName" => $kindName]);
        $allNoteNum = count($allNote);

        $query = $keyName != '' ? 
        function ($query) use ($boderId,$kindName, $dataNum, $keyName, $keyWord) {
            $query->where('kindName', $kindName)->where('id', '>', $boderId)->where($keyName, $keyWord)->order('id', 'asc')->limit($dataNum);
        } :
        function ($query) use ($boderId, $dataNum, $kindName) {
            $query->where('kindName', $kindName)->where('id', '>', $boderId)->order('id', 'asc')->limit($dataNum);
        };
        
        //查询数据
        $allNote = CertifyNeedModel::all($query);
        $allNote = $this->getEnumValue($allNote);

        //返回消息
        $JsonData = controller('index/JsonData');
        $data = [
            'dataTotal' => $allNoteNum,
            'allCertifyNeed' => $allNote
        ];
        $json = $JsonData->getJsonData($status, $message, $data);
        return $json;
    }

    public function addNeed(Request $request)
    {
        //获取请求参数
        $infoName = $request->param('infoName');
        $kindName = $request->param('kindName');
        $belong = $request->param('belong');
        $infoType = $request->param('infoType');
        $chooseValue = $request->param('chooseValue');
        $iconName = $request->param('iconName');

        //初始化数据
        $message = '';
        $status = 0;

        //查询是否存在
        $note = CertifyNeedModel::get(function ($query) use ($kindName, $infoName) {
            $query->where('kindName', $kindName)->where('infoName', $infoName);
        });
        if ($note != NULL) {
            $message .= 'the certify need is exist.';
            $status = 2;
        }   
        else {
            //插入数据

            //首先插入到 certifyNeed 
            $newCertifyNeed = new CertifyNeedModel;
            $newCertifyNeed->belong = $belong;
            $newCertifyNeed->kindName = $kindName;
            $newCertifyNeed->infoType = $infoType;
            $newCertifyNeed->iconName = $iconName;
            $newCertifyNeed->infoName = $infoName;

            if ($newCertifyNeed->save()) {
                $message .= "add certify need success.";
                $status = 0;
            }
            else {
                $message .= 'add certify need fail.';
                $status = 1;
            }

            //然后判断是否是枚举数据，插入到枚举表
            $chooseValue = json_decode($chooseValue, true);
            if (count($chooseValue) > 0 && $infoType == 'enum') {
                $newCertifyNeedEnum = new CertifyNeedEnumModel;
                $list = [];
                foreach ($chooseValue as $key => $value) {
                    $list[] = ['infoName' => $infoName, 'oneValue' => $value, 'kindName' => $kindName];
                }
                $newCertifyNeedEnum->saveAll($list);
            }
            else {
                
            }
            
        }
        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;
        
    }
    public function editNeed(Request $request)
    {
        //获取请求参数
        $id = $request->param('id');
        $infoName = $request->param('infoName');
        $kindName = $request->param('kindName');
        $belong = $request->param('belong');
        $infoType = $request->param('infoType');
        $chooseValue = $request->param('chooseValue');
        $iconName = $request->param('iconName');

        //初始化数据
        $message = '';
        $status = 0;

        $oldCertifyNeed = CertifyNeedModel::get(["id" => $id]);
        $oldCertifyNeed->infoName = $infoName;
        $oldCertifyNeed->kindName = $kindName;
        $oldCertifyNeed->belong = $belong;
        $oldCertifyNeed->infoType = $infoType;
        $oldCertifyNeed->iconName = $iconName;

        if ($oldCertifyNeed->save()) {
            $message = 'update certify need success.';
            $status = 0;
        }
        else {
            $message = 'update certify need fail.';
            $status = 1;
        }

        //判断是否是枚举数据，插入到枚举表
        $chooseValue = json_decode($chooseValue, true);
        if (count($chooseValue) > 0 ) {
            //删除所有的 enum 数据
            $tab = "dcw_fastask_certify_enum_value";
            $delSql = "DELETE FROM $tab WHERE kindName='$kindName' AND infoName='$infoName' ";
            Db::execute($delSql);

            if ($infoType == 'enum') {
                $newCertifyNeedEnum = new CertifyNeedEnumModel;
                //增加
                $list = [];
                foreach ($chooseValue as $key => $value) {
                    $list[] = ['infoName' => $infoName, 'oneValue' => $value, 'kindName' => $kindName];
                }
                $newCertifyNeedEnum->saveAll($list);
            }
            else {
                //不增加
            }
            
        }
        else {
            
        }

        //返回数据
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;
    }

   

    //删除指定认证需要
    public function delCertifyNeed(Request $request)
    {
        //获取请求参数
        $id = $request->param('id');

        //初始化消息
        $message = '';
        $status = 0;
        //判断是否存在
        $oldCertifyNeed = CertifyNeedModel::get(["id" => $id]);
        if ($oldCertifyNeed == NULL) {
            $message = 'the certify need has been delete.';
            $status = 1;
        }
        else {
            //删除相关枚举
            $enumTab = "dcw_fastask_certify_enum_value";
            $needTab = 'dcw_fastask_certify_need';
            $delSql = "DELETE $enumTab FROM $enumTab, $needTab 
                       WHERE $enumTab.kindName = $needTab.kindName 
                       AND $enumTab.infoName = $needTab.infoName 
                       AND $needTab.id = $id
                       AND $needTab.infoType = 'enum'
                       ";
            Db::execute($delSql);

            $oldCertifyNeed->delete();
            $message = 'delete certify need success.';
            $status = 0;
        }
        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;
    }

    //删除所属的所有认证信息
    public function delAllCertifyNeed(Request $request)
    {
        //获取请求参数
        $kindName = $request->param('kindName');

        //初始化消息
        $message = '';
        $status = 0;

        //删除所属下的所有认证以及相关枚举数据
        $enumTab = "dcw_fastask_certify_enum_value";
        $needTab = 'dcw_fastask_certify_need';

        $delNeedSql = "DELETE FROM $needTab WHERE kindName='$kindName' AND infoName != '认证分类'";
        $delEnumSql = "DELETE FROM $enumTab WHERE kindName='$kindName'";
        $status = Db::execute($delNeedSql);
        $status = Db::execute($delEnumSql);

        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;
    }

    //删除选中的选项
    public function delSelection(Request $request)
    {
        //获取请求方式
        $selectId = $request->param("selectId");

        //初始化消息
        $message = '';
        $status = 0;

        //构造sql
        $enumTab = "dcw_fastask_certify_enum_value";
        $needTab = 'dcw_fastask_certify_need';
        $selectId = json_decode($selectId, true);
        foreach ($selectId as $key => $value) {
            $id = $value;
            $delNeed = CertifyNeedModel::get(["id" => $id]);
            $delKindName = $delNeed['kindName'];
            $delInfoName = $delNeed['infoName'];
            $delEnumSql = "DELETE FROM $enumTab WHERE kindName='$delKindName' AND infoName='$delInfoName'";
            $delNeedSql = "DELETE FROM $needTab WHERE id=$id AND infoName!='认证分类'";
            $status = Db::execute($delEnumSql);
            $status = Db::execute($delNeedSql);
            
        }
        $message = 'del select success.';

        //返回消息
        $JsonData = controller('index/JsonData');
        $json = $JsonData->getJsonData($status, $message, array());
        return $json;

    }

    //查询
    public function searchCertifyNeed(Request $request)
    {
        //获取请求参数
        $kindName = $request->param('kindName');
        $keyName = $request->param('keyName');
        $keyWord = $request->param('keyWord');
        $page = $request->param('page');
        $dataNum = $request->param('dataNum');

        //获取边缘 id
        $boderId = $this->getBorderId($dataNum, $page, $kindName);

        //初始化消息
        $message = '';
        $status = 0;

        //查询
        $allNote = CertifyNeedModel::all(function ($query) use ($keyName, $keyWord, $kindName, $boderId, $dataNum) {
            $query->where('kindName', $kindName)->where($keyName, $keyWord)->where('id', '>', $boderId);
        });
    }
}